package ch.so.sogis.interlis;

import java.io.*;
import java.util.concurrent.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.sql.*;

import com.vividsolutions.jump.feature.*;

import org.openjump.core.apitools.IOTools;
import org.openjump.core.apitools.IOTools.*;

import ch.so.sogis.database.*;
import ch.so.sogis.interlis.*;
import ch.so.sogis.interlis.checks.*;
import ch.so.sogis.interlis.converter.*;

class ParallelDM93ToDM01
{
   //Parallel running Threads(Executor) on System
   int corePoolSize = 2;
   
   //Maximum Threads allowed in Pool
   int maxPoolSize = 4;
   
   //Keep alive time for waiting threads for jobs(Runnable)
   long keepAliveTime = 10;
   
   //This is the one who manages and start the work
   ThreadPoolExecutor threadPool = null;
   
   //Working queue for jobs (Runnable). We add them finally here
   final ArrayBlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(55);

   public ParallelDM93ToDM01() {
       threadPool = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.SECONDS, workQueue);
   }
   
   /**
    * Here we add our jobs to working queue
    *
    * @param task a Runnable task
    */
   public void runTask(Runnable task) {
       threadPool.execute(task);
       //System.out.println("Tasks in workQueue.." + workQueue.size());
   }
   
   /**
    * Shutdown the Threadpool if it's finished
    */
   public void shutDown() {
       threadPool.shutdown();
   }
   
   public static void main(String args[]) {
	  
       //String iliFile = "/home/bjsvwzie/tmp_ziegler/interlis/AVS_AV93_SO.ili";
	   String dm93_ili = "/Users/stefan/Geoprojekte/Interlis/AVS_AV93_SO.ili";
	   
	   //String dm93_dir = "/home/bjsvwzie/tmp_ziegler/interlis/dm93alles";
	   String dm93_dir = "/Users/stefan/Geoprojekte/Interlis/dm93";
       
       String[] fileList = new File(dm93_dir).list(new FilenameFilter() {
           public boolean accept(File d, String name) {
               return name.toLowerCase().endsWith(".itf");
           }
       });

       ParallelDM93ToDM01 mtpe = new ParallelDM93ToDM01();
       for(String f : fileList) {
           mtpe.runTask(new WorkerRunnable(f, dm93_ili, dm93_dir));
       }
       mtpe.shutDown();
       System.out.println("Finished!  ");
   }
   
   /**
    * This is the one who do the work
    *
    * This one is static for accessing from main class
    */
   private static class WorkerRunnable implements Runnable {
       private String itf;
       private String dm93_dir;

       private IliReader reader = null;
       private String iliModel;

       private IliWriter writer = null;

       public WorkerRunnable(String itf, String iliModel, String dm93_dir) {
           this.itf = itf;
           this.iliModel = iliModel;
           this.dm93_dir = dm93_dir;

           this.reader = new IliReader(iliModel);
           this.reader.compileModel();

           //this.writer = new IliWriter("/home/bjsvwzie/tmp_ziegler/interlis/DM01AVSO24.ili");
           this.writer = new IliWriter("/Users/stefan/Geoprojekte/Interlis/DM01AVSO24.ili");
           this.writer.compileModel();
       }
       @Override
       public void run() {
           System.out.println("Konvertieren von:  "+itf);
           LinkedHashMap fd_hash = reader.readItf(dm93_dir + "/" + itf , true);
//           System.out.println("Groesse von "+itf+": "+fd_hash.size());

           H2Obj myH2 = new H2Obj();
           Connection conn = myH2.connect(itf);
//           Connection conn = myH2.connect();
           
           Iterator it = fd_hash.entrySet().iterator();
           while(it.hasNext()) {
               Map.Entry ientry = (Map.Entry)it.next();
               String featureName = ientry.getKey().toString();
               FeatureDataset fd = (FeatureDataset) ientry.getValue();
               String tableName = (featureName.substring(featureName.indexOf(".")+1)).replace(".", "_");
               //System.out.println(tableName);
               myH2.insertFeatures(fd, tableName);
           }
           DM93toDM01SO24Converter Converter = new DM93toDM01SO24Converter(conn);
           HashMap fd_conv = Converter.convert();
           
//           Iterator jt = fd_conv.entrySet().iterator();
//           while(jt.hasNext()) {
//        	   Map.Entry jentry = (Map.Entry)jt.next();
//               String featureName = jentry.getKey().toString();
//               FeatureDataset fd = (FeatureDataset) jentry.getValue();
//               try {
//            	   String fname = "/Users/stefan/Geoprojekte/Interlis/dm01conv/"+itf.substring(0, 4)+"_"+featureName;
//            	   System.out.println("Dateiname: "+fname);
//            	   IOTools.saveJMLFile(fd, fname);
//               } catch (Exception e) {
//            	  // e.printStackTrace();
//            	   //System.out.println("Tabelle: "+ featureName + " in Operat: " + itf );
//            	   if(featureName.equalsIgnoreCase("DM01AVSO24.FixpunkteKategorie2.LFP2")) {
//            		   if(itf.equalsIgnoreCase("247300.itf")) {
//            			   System.out.println("LFP2%%%%%%%%%");
//            			   
//            			   Iterator kt = fd.iterator();
//            			   while(kt.hasNext()) {
//            				   BasicFeature f = (BasicFeature) kt.next();
//            				   FeatureSchema schema = f.getSchema();
//            				   int s = schema.getAttributeCount();
//            				   for(int i=0; i<s; i++) {
//            					   System.out.println(schema.getAttributeName(i) +" ("+schema.getAttributeType(i)+   "): "+f.getAttribute(i));
//            				   }
//            				   
//            			   }
//            			   
//            		   }
//            		  
//            	   }
//               }

//           }
           
           
//           System.out.println("Konvertierte Groesse von "+itf+": "+fd_conv.size());
           myH2.close();

//           //writer.writeItf("/home/bjsvwzie/tmp_ziegler/interlis/dm01conv/"+itf, fd_conv);
           writer.writeItf("/Users/stefan/Geoprojekte/Interlis/dm01conv/"+itf, fd_conv);


       }
   }
}
